
package com.yzh.chatgpt.session.impl;

import com.yzh.chatgpt.IOpenAiApi;
import com.yzh.chatgpt.interceptor.ChatInterceptor;
import com.yzh.chatgpt.session.ChatSession;
import com.yzh.chatgpt.session.ChatSessionFactory;
import com.yzh.chatgpt.session.Configuration;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

public class DefaultChatSessionFactory implements ChatSessionFactory {
    private Configuration configuration;

    public DefaultChatSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public ChatSession getChatSession() {
        //1.日志配置，HEADERS：输出网络请求的日志信息
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

        //2.创建Http客户端，用来发送和接收网络请求
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                //日志拦截
                .addInterceptor(httpLoggingInterceptor)
                //自定义拦截
                .addInterceptor(new ChatInterceptor(configuration.getApiKey(), configuration.getAuthToken()))
                //连接、写入和读取的超时时间450秒
                .connectTimeout(450, TimeUnit.SECONDS)
                .writeTimeout(450, TimeUnit.SECONDS)
                .readTimeout(450, TimeUnit.SECONDS)
                .build();

        //3.创建API服务，Retrofit对象
        IOpenAiApi openAiApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build().create(IOpenAiApi.class);
        return new DefaultChatSession(openAiApi);
    }
}
